<template>
    <div class="login_box">
        <span>登录到者也</span>
        <From :fromData="fromOut" sumbit="登录" @onSumbit="testClick" />
        <router-link to="/regist">没有账号？去注册</router-link>
    </div>
</template>

<script lang='ts'>
import From, { FromProps } from '../../components/From/index.vue'
import { defineComponent } from 'vue'
import { reqUserLogin, TypeResUserData } from '../../api/main'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { Message } from '../../coustom/Message'
interface FromData {
    email: string
    password: string
}
export default defineComponent({
    name: 'Login',
    components: { From },
    setup() {
        const { query } = useRoute()
        const store = useStore()
        const { replace } = useRouter()
        const fromOut: FromProps = [
            {
                titel: '邮箱',
                valueKey: 'email',
                defult: '请输入邮箱',
                rules: [
                    {
                        type: 'required',
                        text: '邮箱是必填的'
                    },
                    {
                        type: 'mail',
                        text: '请输入正确的邮箱格式'
                    }
                ]
            },
            {
                titel: '密码',
                valueKey: 'password',
                defult: '请输入密码',
                inputType: 'password',
                rules: [
                    {
                        type: 'required',
                        text: '密码是必填的'
                    },
                ],
                custom(value) {
                    if (value.length < 6) return '密码长度过低'
                    return false
                }
            }
        ]
        const testClick = async (value: FromData | false) => {
            if (value) {
                try {
                    const { data: { token } } = await reqUserLogin(value) as unknown as TypeResUserData
                    localStorage.setItem('token', token)
                    await store.dispatch('getUsetData')
                    Message.success('登录成功，为您自动跳转')
                    if (query.path) {
                        replace({
                            path: query.path as string
                        })
                    } else {
                        replace({
                            path: "/"
                        })
                    }

                } catch {
                    Message.error('密码或者账号错误')

                }
            }
        }
        return { fromOut, testClick }
    }
})
</script>
<style scoped lang='less'>
.login_box {
    width: 50%;
    min-height: 500px;
    display: flex;
    margin: 0 auto;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    span {
        font-size: 25px;
        margin-bottom: 30px;
    }
}
</style>